#include "display.h"
#include "screenmap_v1_interface_p.h"
#include "output_interface.h"

#include <QDebug>

namespace KWaylandServer
{

const quint32 ScreenMapV1InterfacePrivate::s_version = 1;

ScreenMapV1InterfacePrivate::ScreenMapV1InterfacePrivate(ScreenMapV1Interface *_q, Display *display)
    : QtWaylandServer::zwp_screen_map_manager_v1(*display, s_version)
    , q(_q)
    , display(display)
{
}

ScreenMapV1InterfacePrivate::~ScreenMapV1InterfacePrivate()
{
}

void ScreenMapV1InterfacePrivate::zwp_screen_map_manager_v1_get_screen_names(Resource *resource)
{
    auto outputs = display->outputs();

    QString str;
    for (int i = 0; i < outputs.size(); i++) {
        if (outputs[i]->model() == QString::fromUtf8("none")) {
            continue;
        }
        if (i < outputs.size() - 1) {
            str = str + outputs[i]->model() + QString::fromUtf8(":");
        } else {
            str = str + outputs[i]->model();
        }
    }

	send_screen_names(resource->handle, str);
}

void ScreenMapV1InterfacePrivate::zwp_screen_map_manager_v1_get_touch_ids(Resource *resource)
{
    auto touch_device = display->getTouchDeviceIds();

    QStringList strList;
    for (auto it : touch_device.keys()) {
        strList.append(QString::number(it));
    }
    QString str = strList.join(QString::fromUtf8(":"));

    send_touch_ids(resource->handle, str);
}
void ScreenMapV1InterfacePrivate::zwp_screen_map_manager_v1_get_touch_product_vendor(Resource *resource, uint32_t touchId)
{
    if (touchId <= 0) {
        return;
    }

    auto touch_device = display->getTouchDeviceIds();
    auto tmp = touch_device.find(touchId);
    QString str;
    if (tmp != touch_device.end()) {
        str = QString::number(tmp.value().first) + QString::fromUtf8(":") + QString::number(tmp.value().second);
    } else {
        str = QString();
    }

    send_touch_product_vendor(resource->handle, str);
}
void ScreenMapV1InterfacePrivate::zwp_screen_map_manager_v1_set_screen_map_status(Resource *resource, int32_t touchId, const QString &screenName)
{
    qDebug() << "server receive reqest touchScreen" << touchId << "mapToScreen" << screenName;

    auto touch_device = display->getTouchDeviceIds();
    if (!touch_device.contains(touchId)) {
        return;
    }
    QString screen = screenName;
    auto outputs = display->outputs();
    int i;
    for (i = 0; i < outputs.size(); i++) {
        QString str = outputs[i]->model();
        int length = str.length() < screen.length() ? str.length() : screen.length();
        if (str.left(length) != screen.left(length)) {
            continue;
        } else {
            break;
        }
    }
    if (i == outputs.size()) {
        return;
    }
    Q_EMIT q->screenMapStatusChange(touchId, screen);
}

ScreenMapV1Interface::ScreenMapV1Interface(Display *display, QObject *parent)
    : QObject(parent)
    , d(new ScreenMapV1InterfacePrivate(this, display))
{
}

ScreenMapV1Interface::~ScreenMapV1Interface() = default;

}